package com.smartfactory.sail.controller;


import com.ada.base.common.ApiResponse;
import com.ada.base.common.ControllerResponse;
import com.ada.base.common.ResultData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smartfactory.sail.config.HeaderWrapper;
import com.smartfactory.sail.config.OperRecord;
import com.smartfactory.sail.constant.header.MaterialEnum;
import com.smartfactory.sail.constant.header.ProductEnum;
import com.smartfactory.sail.dto.InspectioncriteriaDto;
import com.smartfactory.sail.entity.Cust;
import com.smartfactory.sail.entity.Item;
import com.smartfactory.sail.entity.ItemInspectioncriteria;
import com.smartfactory.sail.entity.enums.ItemStatusEnum;
import com.smartfactory.sail.mapper.ItemMapper;
import com.smartfactory.sail.mapper.ItemMaterialMapper;
import com.smartfactory.sail.service.ICustService;
import com.smartfactory.sail.service.IItemInspectioncriteriaService;
import com.smartfactory.sail.service.IItemService;
import com.smartfactory.sail.vo.PageParam;
import com.smartfactory.sail.vo.item.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 物料表,生产原料,原料,产品表 前端控制器
 * </p>
 *
 * @author 王巨壁
 * @since 2019-07-24
 */
@Api(tags = "产品-原料 相关")
@RestController
@RequestMapping("/item")
public class ItemController extends ControllerResponse {

    private IItemService iItemService;

    private ItemMapper itemMapper;
    private IItemInspectioncriteriaService iItemInspectioncriteriaService;
    private ICustService iCustService;
    private ItemMaterialMapper itemMaterialMapper;

    public ItemController(IItemService iItemService, ItemMapper itemMapper, IItemInspectioncriteriaService iItemInspectioncriteriaService, ICustService iCustService, ItemMaterialMapper itemMaterialMapper) {
        this.iItemService = iItemService;
        this.itemMapper = itemMapper;
        this.iItemInspectioncriteriaService = iItemInspectioncriteriaService;
        this.iCustService = iCustService;
        this.itemMaterialMapper = itemMaterialMapper;
    }

    @OperRecord(content = "新增产品", level = 1)
    @PostMapping("/product/add")
    @ApiOperation(value = "产品新增", notes = "产品新增")
    public ApiResponse<Object> add(@Validated @RequestBody AddProjectReq req) {
        //产品编码不能重复
        @NotBlank String code = req.getCode();
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("code", code);
        if (iItemService.count(itemQueryWrapper) > 0) {
            return fail("产品编码已经存在");
        }
        Long aLong = iItemService.addProduct(req, ItemStatusEnum.ZC);
        if (aLong > 0) {
            return ok(aLong);
        }
        return fail(ResultData.FAIL_CODE_MSG);
    }

    @OperRecord(content = "新增原料", level = 1)
    @PostMapping("/material/add")
    @ApiOperation(value = "原料新增", notes = "原料新增")
    public ApiResponse<Object> add(@RequestBody AddMaterialReq req) {
        //产品编码不能重复
        @NotBlank String code = req.getCode();
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("code", code);
        if (iItemService.count(itemQueryWrapper) > 0) {
            return fail("产品编码已经存在");
        }
        Long aLong = iItemService.addMaterial(req);
        if (aLong > 0) {
            return ok(aLong);
        }
        return fail(ResultData.FAIL_CODE_MSG);
    }

    @OperRecord(content = "修改原料信息", level = 1)
    @PostMapping("/material/update")
    @ApiOperation(value = "修改原料信息", notes = "修改原料信息")
    public ApiResponse<Boolean> updateMaterial(@RequestBody UpdateMaterialReq req) {
        Item item = new Item();
        BeanUtils.copyProperties(req, item);
        if (iItemService.updateById(item)) {
            //删除检验规则 再添加
            UpdateWrapper<ItemInspectioncriteria> del = new UpdateWrapper<>();
            del.eq("itemId", req.getId());
            iItemInspectioncriteriaService.remove(del);
            ArrayList<ItemInspectioncriteria> itemInspectioncriteria = new ArrayList<>();
            for (InspectioncriteriaDto inspectioncriteriaDto : req.getInspectioncriteriaList()) {
                ItemInspectioncriteria ii = new ItemInspectioncriteria();
                BeanUtils.copyProperties(inspectioncriteriaDto, ii);
                ii.setItemId(req.getId());
                itemInspectioncriteria.add(ii);
            }
            iItemInspectioncriteriaService.saveBatch(itemInspectioncriteria);

        } else {
            return fail("修改失败");
        }
        return ok(true);
    }

    @HeaderWrapper(ProductEnum.class)
    @ApiOperation(value = "产品列表 分页|currentPage|size|sortType|sortField 必传", notes = "产品列表 分页|currentPage|size|sortType|sortField 必传")
    @PostMapping("listProduct/{currentPage}/{size}/{sortType}/{sortField}")
    public ApiResponse<Object> listProduct(@RequestBody Map<String, Object> queryParam,
                                           @PathVariable("currentPage") Long currentPage,
                                           @PathVariable("size") Integer size,
                                           @PathVariable("sortType") Integer sortType,
                                           @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        queryParam.put("itemMode", 1);
        return ok(iItemService.listItem(queryParam, pageParam));
    }

    @HeaderWrapper(MaterialEnum.class)
    @ApiOperation(value = "原料列表 分页|currentPage|size|sortType|sortField 必传", notes = "原料列表 分页|currentPage|size|sortType|sortField 必传")
    @PostMapping("listMaterial/{currentPage}/{size}/{sortType}/{sortField}")
    public ApiResponse<IPage<ListMaterialResp>> listMaterial(@RequestBody Map<String, Object> queryParam,
                                                             @PathVariable("currentPage") Long currentPage,
                                                             @PathVariable("size") Integer size,
                                                             @PathVariable("sortType") Integer sortType,
                                                             @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        return ok(iItemService.listMaterials(queryParam, pageParam));
    }


    @ApiOperation(value = "所有产品-下拉框", notes = "所有产品-下拉框")
    @GetMapping("listItems")
    public ApiResponse<Object> listItems() {
        return ok(itemMapper.getAllItemSampleList());
    }

    @ApiOperation(value = "所有原料-下拉框", notes = "所有原料-下拉框")
    @GetMapping("getAllMaterials")
    public ApiResponse<Object> listMaterial() {
        return ok(itemMapper.getAllMaterials());
    }


    @ApiOperation(value = "根据产品id获取详情", notes = "根据产品id获取详情")
    @GetMapping("productInfo/{id}")
    public ApiResponse<ProjectInfoResp> productInfo(@PathVariable("id") Long id) {
        return ok(iItemService.getProductInfoById(id));
    }

    @ApiOperation(value = "获取所有录入过的供应商列表", notes = "获取所有录入过的供应商列表")
    @GetMapping("getSuppliers")
    public ApiResponse<HashSet<String>> getSuppliers() {
        String suppliers = itemMapper.getSuppliers();
        HashSet<String> result = new HashSet<>();
        if (StringUtils.hasText(suppliers)) {
            Arrays.stream(suppliers.trim().split(",")).map(s ->
                    Arrays.stream(s.trim().split("\\|")).filter(s1 -> !"".equals(s1)).collect(Collectors.toSet())
            ).forEach(result::addAll);
        }
        return ok(result);
    }

    @OperRecord(content = "修改产品状态(在产停产)", level = 1)
    @ApiOperation(value = "修改产品状态", notes = "修改产品状态-在产-停产")
    @GetMapping("updateProductStatus/{itemId}/{status}")
    public ApiResponse<Boolean> updateProductStatus(@PathVariable("itemId") Long itemId, @PathVariable("status") String status) {
        Item item = new Item();
        item.setId(itemId);
        ItemStatusEnum itemStatusEnum = ItemStatusEnum.valueOf(status);
        item.setStatus(itemStatusEnum);
        if (iItemService.updateById(item)) {
            return ok();
        }
        return fail("修改失败");
    }


    @ApiOperation(value = "根据id获取原料详情", notes = "根据id获取原料详情")
    @PostMapping("/getMaterialsInfoById/{itemId}")
    public ApiResponse<MaterialInfoResp> getMaterialsInfoById(@PathVariable("itemId") Long itemId) {

        MaterialInfoResp resp = new MaterialInfoResp();
        Item byId = iItemService.getById(itemId);
        if (byId != null) {
            resp.setCode(byId.getCode());
            resp.setName(byId.getName());
            resp.setProductDrawings(byId.getProductDrawings());
            resp.setTexture(byId.getTexture());
            String suppliers = byId.getSuppliers();
            ArrayList<Cust> custs = new ArrayList<>();
            if (suppliers != null && !"".equals(suppliers)) {
                String[] split = suppliers.split("\\|");
                for (String s : split) {
                    custs.add(iCustService.getById(Long.valueOf(s)));
                }
            }
            resp.setSuppliers(custs);
            QueryWrapper<ItemInspectioncriteria> query = new QueryWrapper<>();
            query.eq("itemId", itemId);
            List<ItemInspectioncriteria> list = iItemInspectioncriteriaService.list(query);
            ArrayList<InspectioncriteriaDto> inspectioncriteriaDtos = new ArrayList<>();
            for (ItemInspectioncriteria itemInspectioncriteria : list) {
                InspectioncriteriaDto inspectioncriteriaDto = new InspectioncriteriaDto();
                BeanUtils.copyProperties(itemInspectioncriteria, inspectioncriteriaDto);
                inspectioncriteriaDtos.add(inspectioncriteriaDto);
            }
            resp.setInspectioncriteriaList(inspectioncriteriaDtos);
            return ok(resp);
        }
        return fail("未查询到匹配数据");
    }

    @ApiOperation(value = "获取所有在产产品列表", notes = "获取所有在产产品列表 配合新增合同订单选择使用")
    @GetMapping("/getProductByDoing")
    public ApiResponse<List<GetProductByDoingResp>> getProductByDoing() {
        QueryWrapper<Item> quet = new QueryWrapper<>();
        quet.eq("itemMode", 1).eq("status", 1);
        List<Item> list = iItemService.list(quet);
        ArrayList<GetProductByDoingResp> result = new ArrayList<>();
        for (Item item : list) {
            GetProductByDoingResp res = new GetProductByDoingResp();
            res.setId(item.getId());
            res.setCode(item.getCode());
            res.setCustDrawings(item.getCustDrawings());
            res.setInfo(item.getInfo());
            res.setName(item.getName());
            res.setProductDrawings(item.getProductDrawings());
            res.setTechnicalDrawings(item.getTechnicalDrawings());
            result.add(res);
        }
        return ok(result);
    }

    @ApiOperation(value = "根据产品id 获取所有原料", notes = "根据产品id 获取所有原料")
    @GetMapping("/getMaterialsByProductId/{itemId}")
    public ApiResponse<List<Item>> getMaterialsByProductId(@PathVariable("itemId") Long itemId) {
        return ok(itemMaterialMapper.listMaterialsByProductId(itemId));
    }
}
